package com.moss.cloud.auth.biz.config;

import com.google.common.collect.Maps;
import com.moss.cloud.auth.biz.model.UserPrincipal;
import com.moss.cloud.common.core.enums.GrantTypeEnum;
import com.moss.cloud.common.core.utils.BooleanHandel;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.Date;
import java.util.Map;

/**
 * 自定义token携带内容
 *
 * @author 瑾年
 * @data 2023年3月6
 */
public class CustomTokenEnhancer implements TokenEnhancer {

    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = Maps.newHashMap();
        BooleanHandel.isTrue(this.checkGrantType(authentication))
                .trueHandle(() -> {
                    //自定义token内容
                    UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
                    additionalInfo.put("tenantId", userPrincipal.getTenantId());
                    additionalInfo.put("userId", userPrincipal.getUserId());
                    additionalInfo.put("deptId", userPrincipal.getDeptId());
                    additionalInfo.put("roleIds", userPrincipal.getRoleIds());
                    additionalInfo.put("roleCodes", userPrincipal.getRoleCodes());
                });
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        ((DefaultOAuth2AccessToken) accessToken).setExpiration(new Date(System.currentTimeMillis() + 90000000));
        return accessToken;
    }

    private Boolean checkGrantType(OAuth2Authentication authentication) {
        Map<String, String> oauth2Params = authentication.getOAuth2Request().getRequestParameters();
        Boolean grantType = oauth2Params.containsKey(GrantTypeEnum.GRANT_TYPE.getValue());
        return grantType ? (!oauth2Params.get(GrantTypeEnum.GRANT_TYPE.getValue()).equals(GrantTypeEnum.CLIENT.getValue()) &&
                !oauth2Params.get(GrantTypeEnum.GRANT_TYPE.getValue()).equals(GrantTypeEnum.CODE.getValue())) : Boolean.TRUE;
    }
}